Introduction to Java Operators and Expressions
Course: Core Java Training
Topic: Introduction to Java Operators and Expressions
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to Java Operators and Expressions
Operators and expressions are fundamental parts of Java programming. They allow developers to perform calculations, compare values, assign data, check conditions, manipulate bits, and control how values are processed in a program.
An operator is a symbol or token that performs an operation on one or more values. An expression is a combination of values, variables, method calls, and operators that is evaluated to produce a result.
For example:
int a = 10;
int b = 5;
int sum = a + b;
In this example, + is an operator, and a + b is an expression. The expression evaluates to 15, which is assigned to the variable sum.
Understanding operators and expressions is essential for writing programs that calculate results, validate user input, implement business rules, and make decisions.
2. Learning Objectives
After studying this topic, you should be able to:
- Define operators and expressions in Java.
- Understand operands and how operators work with them.
- Use arithmetic operators for mathematical calculations.
- Apply assignment and compound assignment operators.
- Compare values using relational and equality operators.
- Build logical expressions using boolean operators.
- Use unary, increment, decrement, and conditional operators.
- Understand bitwise and shift operators.
- Apply operator precedence and associativity.
- Recognize type conversion, integer division, and short-circuit evaluation.
- Identify common operator-related errors and follow coding best practices.
3. What Is an Operator?
An operator is a symbol or token that instructs Java to perform an operation on one or more operands. Operands are the values or expressions on which an operator acts.
Example
int result = 12 + 8;
12 is an operand.
8 is an operand.
+ is the operator.
12 + 8 is the expression.
result is the variable that receives the computed value.
Operators Based on Number of Operands
| Type |
Description |
Example |
| Unary |
Works with one operand. |
-number |
| Binary |
Works with two operands. |
a + b |
| Ternary |
Uses three operands in a conditional expression. |
age >= 18 ? "Adult" : "Minor" |
4. What Is an Expression?
An expression is a valid combination of operands, operators, and sometimes method calls that produces a value. Expressions can be simple or complex.
Simple Expression
int total = 10 + 20;
The expression 10 + 20 produces the value 30.
Expression Using Variables
int price = 500;
int quantity = 3;
int totalCost = price * quantity;
The expression price * quantity multiplies the price by the quantity, producing 1500.
Expression Using Comparison
int marks = 75;
boolean passed = marks >= 40;
The expression marks >= 40 evaluates to true, so passed receives the boolean value true.
Expression Using Multiple Operators
int result = 10 + 5 * 2;
The multiplication operator has higher precedence than addition, so Java evaluates 5 * 2 first. The final result is 20, not 30.
5. Categories of Java Operators
Java provides several operator categories, each designed for a particular type of operation.
| Category |
Operators |
Purpose |
| Arithmetic |
+, -, *, /, % |
Perform mathematical calculations. |
| Unary |
+, -, ++, --, !, ~ |
Operate on a single operand. |
| Relational |
<, >, <=, >= |
Compare numeric values or compatible values. |
| Equality |
==, != |
Test equality or inequality. |
| Logical |
&&, ||, ! |
Combine or reverse boolean conditions. |
| Bitwise |
&, |, ^, ~ |
Operate on individual bits. |
| Shift |
<<, >>, >>> |
Shift bits left or right. |
| Assignment |
=, +=, -=, *=, /=, %= |
Assign or update variable values. |
| Conditional |
? : |
Select one of two expressions based on a condition. |
| Type comparison |
instanceof |
Check whether an object is compatible with a specified type. |
6. Arithmetic Operators
Arithmetic operators perform mathematical calculations on numeric values. They are commonly used in billing systems, marks calculations, financial applications, unit conversions, and data processing.
| Operator |
Name |
Example |
Result |
+ |
Addition |
10 + 5 |
15 |
- |
Subtraction |
10 - 5 |
5 |
* |
Multiplication |
10 * 5 |
50 |
/ |
Division |
10 / 5 |
2 |
% |
Remainder |
10 % 3 |
1 |
6.1 Addition Operator (+)
The addition operator adds two numeric values. When one operand is a string, + can instead concatenate text.
int a = 15;
int b = 10;
System.out.println(a + b);
System.out.println("Java " + "Programming");
Output:
25
Java Programming
6.2 Subtraction Operator (-)
The subtraction operator calculates the difference between two numeric values.
int totalMarks = 100;
int obtainedMarks = 82;
int remainingMarks = totalMarks - obtainedMarks;
System.out.println(remainingMarks);
Output: 18
6.3 Multiplication Operator (*)
The multiplication operator multiplies two numeric operands.
int price = 250;
int quantity = 4;
int totalPrice = price * quantity;
System.out.println(totalPrice);
Output: 1000
6.4 Division Operator (/)
The division operator divides one numeric value by another. The result depends on the operand types.
int a = 10;
int b = 3;
System.out.println(a / b);
System.out.println(10.0 / 3);
Output:
3
3.3333333333333335
When both operands are integers, Java performs integer division and discards the fractional part of the result. If at least one operand is floating-point, the operation uses floating-point arithmetic.
6.5 Remainder Operator (%)
The remainder operator returns the remainder after division. It is useful for checking even and odd numbers and for working with repeating cycles.
int number = 17;
System.out.println(number % 5);
System.out.println(10 % 2);
System.out.println(11 % 2);
Output:
2
0
1
A remainder of zero when dividing an integer by two indicates that the number is even.
Important Arithmetic Considerations
- Integer division truncates toward zero.
- Integer division or remainder by zero throws
ArithmeticException.
- Floating-point calculations may contain rounding errors.
- Integer arithmetic can overflow when the result exceeds the representable range.
- For accurate monetary calculations, consider using
BigDecimal with a suitable rounding policy instead of relying on binary floating-point values.
7. Unary Operators
Unary operators act on one operand. They can change a value's sign, increment or decrement a variable, or reverse a boolean value.
| Operator |
Purpose |
Example |
+ |
Unary plus; indicates a positive value. |
+number |
- |
Unary minus; negates a numeric value. |
-number |
++ |
Increments a variable by one. |
count++ |
-- |
Decrements a variable by one. |
count-- |
! |
Reverses a boolean value. |
!isActive |
~ |
Inverts the bits of an integral value. |
~number |
7.1 Unary Plus and Minus
int number = 10;
System.out.println(+number);
System.out.println(-number);
Output:
10
-10
7.2 Increment Operator (++ )
The increment operator increases a variable's value by one.
int count = 5;
count++;
System.out.println(count);
Output: 6
7.3 Decrement Operator (-- )
The decrement operator decreases a variable's value by one.
int count = 5;
count--;
System.out.println(count);
Output: 4
7.4 Logical NOT Operator (!)
The logical NOT operator reverses a boolean value: true becomes false, and false becomes true.
boolean isLoggedIn = true;
System.out.println(!isLoggedIn);
Output: false
8. Prefix and Postfix Increment and Decrement
Increment and decrement operators can be placed before or after a variable. The difference matters when the expression's value is used as part of a larger expression.
- Prefix: The variable is updated first, and the expression produces the updated value.
- Postfix: The expression produces the original value, and the variable is then updated.
Prefix Example
int a = 5;
int result = ++a;
System.out.println(a);
System.out.println(result);
Output:
6
6
Postfix Example
int a = 5;
int result = a++;
System.out.println(a);
System.out.println(result);
Output:
6
5
In both cases, a becomes 6. However, the value assigned to result differs because prefix and postfix expressions produce different values.
9. Relational Operators
Relational operators compare numeric values and produce a boolean result. They are frequently used in if statements, loops, and validation logic.
| Operator |
Meaning |
Example |
Result |
< |
Less than |
5 < 10 |
true |
> |
Greater than |
15 > 10 |
true |
<= |
Less than or equal to |
10 <= 10 |
true |
>= |
Greater than or equal to |
8 >= 10 |
false |
Example
int age = 21;
System.out.println(age >= 18);
System.out.println(age < 18);
Output:
true
false
10. Equality Operators
Java uses == to test equality and != to test inequality. Their behavior depends on the types being compared.
int a = 10;
int b = 10;
int c = 20;
System.out.println(a == b);
System.out.println(a != c);
Output:
true
true
Comparing Objects
For reference types, == checks whether two references point to the same object, not whether two different objects contain equal data.
String first = new String("Java");
String second = new String("Java");
System.out.println(first == second);
System.out.println(first.equals(second));
Output:
false
true
The references refer to distinct objects, so == returns false. The equals() method on String compares the character content, so it returns true.
11. Logical Operators
Logical operators combine or reverse boolean expressions. They are essential for implementing conditions involving multiple requirements.
| Operator |
Name |
Behavior |
&& |
Logical AND |
True only when both operands are true; skips the right operand if the left is false. |
|| |
Logical OR |
True when at least one operand is true; skips the right operand if the left is true. |
! |
Logical NOT |
Reverses a boolean value. |
11.1 Logical AND (&&)
int age = 25;
boolean hasLicense = true;
System.out.println(age >= 18 && hasLicense);
Output: true
Both conditions must be true for the entire expression to evaluate to true.
11.2 Logical OR (||)
boolean isWeekend = false;
boolean isHoliday = true;
System.out.println(isWeekend || isHoliday);
Output: true
Only one of the conditions needs to be true for the expression to evaluate to true.
11.3 Logical NOT (!)
boolean isAvailable = false;
System.out.println(!isAvailable);
Output: true
12. Short-Circuit Evaluation
Java's conditional logical operators && and || use short-circuit evaluation. This means Java evaluates the right operand only when it is necessary to determine the result.
Example Using AND
int number = 0;
if (number != 0 && 10 / number > 1) {
System.out.println("Condition is true");
} else {
System.out.println("Condition is false");
}
Output: Condition is false
Because number != 0 is false, Java does not evaluate 10 / number. This prevents division by zero in the second operand.
Example Using OR
boolean isAdmin = true;
if (isAdmin || checkPermission()) {
System.out.println("Access granted");
}
If isAdmin is true, Java does not call checkPermission() because the overall OR expression is already true. The method must be defined if this example is used in a complete program.
Logical Operators Versus Boolean Bitwise Operators
The operators & and | can also operate on boolean operands. Unlike && and ||, they evaluate both operands. Prefer the conditional operators for ordinary boolean conditions unless evaluating both operands is intentional.
13. Assignment Operators
The assignment operator stores a value in a variable. Compound assignment operators combine an operation with assignment.
| Operator |
Equivalent Form |
Example |
= |
Assign a value |
x = 10; |
+= |
x = x + value; |
x += 5; |
-= |
x = x - value; |
x -= 3; |
*= |
x = x * value; |
x *= 2; |
/= |
x = x / value; |
x /= 4; |
%= |
x = x % value; |
x %= 3; |
Example
int balance = 100;
balance += 50;
System.out.println(balance);
balance -= 20;
System.out.println(balance);
balance *= 2;
System.out.println(balance);
Output:
150
130
260
Compound assignments can include implicit narrowing conversions that an equivalent expanded assignment would not allow. For example, byte b = 5; b += 2; is valid, while b = b + 2; requires an explicit cast because b + 2 is evaluated as an int.
14. Conditional (Ternary) Operator
The conditional operator ? : selects one of two expressions based on a boolean condition. It provides a compact alternative to some simple if-else statements.
Syntax
condition ? expressionIfTrue : expressionIfFalse;
Example
int age = 20;
String category = age >= 18 ? "Adult" : "Minor";
System.out.println(category);
Output: Adult
Equivalent if-else Statement
int age = 20;
String category;
if (age >= 18) {
category = "Adult";
} else {
category = "Minor";
}
Use the ternary operator for short, clear choices. Deeply nested ternary expressions can make code difficult to read, so use ordinary conditional statements when the logic becomes complex.
```html
15. Bitwise Operators
Bitwise operators work on the individual bits of integral numeric values such as byte, short, int, and long. They are useful in low-level programming, flags, permissions, and certain data-processing tasks.
| Operator |
Name |
Purpose |
& |
Bitwise AND |
Sets a result bit to 1 when both corresponding bits are 1. |
| |
Bitwise OR |
Sets a result bit to 1 when either corresponding bit is 1. |
^ |
Bitwise XOR |
Sets a result bit to 1 when the corresponding bits differ. |
~ |
Bitwise complement |
Inverts every bit of an integral value. |
15.1 Bitwise AND (&)
int a = 6; // Binary: 0110
int b = 3; // Binary: 0011
System.out.println(a & b);
Output: 2
Only the second bit from the right is 1 in both operands, so the result is binary 0010, which equals decimal 2.
15.2 Bitwise OR (|)
int a = 6; // Binary: 0110
int b = 3; // Binary: 0011
System.out.println(a | b);
Output: 7
The result is binary 0111, which equals decimal 7.
15.3 Bitwise XOR (^)
int a = 6; // Binary: 0110
int b = 3; // Binary: 0011
System.out.println(a ^ b);
Output: 5
The result is binary 0101, which equals decimal 5. XOR produces 1 when the corresponding bits differ.
15.4 Bitwise Complement (~)
int number = 5;
System.out.println(~number);
Output: -6
For Java's signed two's-complement integer representation, the bitwise complement of an integer x equals -x - 1.
16. Shift Operators
Shift operators move the bits of an integral value to the left or right. They are often used in bit manipulation, masks, and performance-sensitive algorithms where their behavior is appropriate.
| Operator |
Name |
Behavior |
<< |
Left shift |
Shifts bits to the left and fills the rightmost positions with zeros. |
>> |
Signed right shift |
Shifts bits to the right and preserves the sign bit. |
>>> |
Unsigned right shift |
Shifts bits to the right and fills the leftmost positions with zeros. |
16.1 Left Shift
int number = 5;
System.out.println(number << 1);
System.out.println(number << 2);
Output:
10
20
For this example, shifting 5 left by one position produces 10, and shifting it left by two positions produces 20. However, overflow and the fixed width of integer types mean that left shifts should not always be treated as ordinary multiplication.
16.2 Signed Right Shift
int number = 16;
System.out.println(number >> 2);
Output: 4
For this positive value, shifting right by two positions produces 4. For negative numbers, signed right shift preserves the sign bit.
16.3 Unsigned Right Shift
int number = -8;
System.out.println(number >> 1);
System.out.println(number >>> 1);
The two results differ because >> preserves the sign bit, whereas >>> fills the leftmost bits with zeros. The unsigned-shift result for an int is a nonnegative value representing the shifted 32-bit pattern.
17. The instanceof Operator
The instanceof operator checks whether an object reference is compatible with a specified type. It commonly appears in inheritance, object-oriented programming, and runtime type checks.
Example
Object value = "Hello Java";
System.out.println(value instanceof String);
System.out.println(value instanceof Integer);
Output:
true
false
The object referred to by value is a String, so the first expression is true. It is not an Integer, so the second expression is false.
In modern Java versions, pattern matching can also combine a type check with a variable declaration:
Object value = "Hello Java";
if (value instanceof String text) {
System.out.println(text.length());
}
Output: 10
The variable text is available in the appropriate scope when the pattern match succeeds.
18. Operator Precedence and Associativity
Operator precedence determines which operators are grouped first in an expression. Associativity determines how operators of the same precedence are grouped when parentheses do not specify otherwise.
Example of Precedence
int result = 10 + 5 * 2;
System.out.println(result);
Output: 20
Multiplication has higher precedence than addition, so Java groups the expression as 10 + (5 * 2).
Using Parentheses
int result = (10 + 5) * 2;
System.out.println(result);
Output: 30
Parentheses explicitly control the grouping and make expressions easier to understand.
Common Operator Precedence Order
The table below shows a simplified precedence order, from higher precedence to lower precedence. Operators on the same row generally have the same precedence.
| Precedence |
Operators |
Associativity or Notes |
| Highest |
Parentheses (), array access, member access, method invocation |
Parentheses explicitly group expressions. |
| Unary |
++, --, unary +, unary -, !, ~, casts |
Unary operators group according to their syntax. |
| Multiplicative |
*, /, % |
Left to right. |
| Additive |
+, - |
Left to right. |
| Shift |
<<, >>, >>> |
Left to right. |
| Relational |
<, >, <=, >=, instanceof |
Left to right; relational expressions cannot be chained like mathematical inequalities. |
| Equality |
==, != |
Left to right. |
| Bitwise AND |
& |
Higher than bitwise XOR and OR. |
| Bitwise XOR |
^ |
Higher than bitwise OR. |
| Bitwise OR |
| |
Higher than conditional logical AND. |
| Logical AND |
&& |
Higher than logical OR. |
| Logical OR |
|| |
Higher than the conditional operator. |
| Conditional |
? : |
Groups from right to left. |
| Assignment |
=, +=, -=, *=, /=, %=, and other assignment operators |
Groups from right to left. |
| Lowest among those listed |
Lambda arrow -> in relevant expression grammar |
Has its own syntax and context rules. |
This is a learning summary, not a complete grammar specification. When expressions become complex, use parentheses instead of relying on memorized precedence.
Associativity Example
int result = 20 - 5 - 3;
System.out.println(result);
Output: 12
Subtraction groups from left to right: (20 - 5) - 3.
Assignment Associativity Example
int a, b, c;
a = b = c = 10;
System.out.println(a);
System.out.println(b);
System.out.println(c);
Output:
10
10
10
Assignment groups from right to left, so c receives 10 first, then b, then a.
19. Type Conversion and Numeric Promotion
Java sometimes converts operand types automatically before performing an operation. Understanding these conversions helps prevent unexpected results and compilation errors.
19.1 Integer Division
int a = 7;
int b = 2;
System.out.println(a / b);
System.out.println((double) a / b);
Output:
3
3.5
The first expression uses integer division. The second converts a to double before division.
19.2 Numeric Promotion
For many arithmetic operations, Java promotes smaller integral types such as byte, short, and char to int. If an expression includes a long, float, or double operand, the operation may use the corresponding wider type.
byte a = 10;
byte b = 20;
int result = a + b;
System.out.println(result);
Output: 30
The addition expression is evaluated as an int, so assigning it to an int variable is valid.
19.3 Explicit Casting
double price = 99.95;
int roundedDown = (int) price;
System.out.println(roundedDown);
Output: 99
Casting a floating-point value to an integer type discards the fractional part toward zero. It does not perform conventional rounding.
20. Common Mistakes When Using Operators
Mistake 1: Confusing Assignment and Equality
int number = 10; // Assignment
System.out.println(number == 10); // Equality comparison
Explanation: = assigns a value, whereas == compares values or references, depending on their types.
Mistake 2: Expecting Decimal Division from Integers
System.out.println(5 / 2);
Output: 2
Correction: Use a floating-point operand when a fractional result is required, for example 5.0 / 2.
Mistake 3: Using == to Compare String Content
String first = new String("Java");
String second = new String("Java");
System.out.println(first == second);
Explanation: The expression compares object references, not string content. Use first.equals(second) to compare string content when both references are non-null.
Mistake 4: Ignoring Operator Precedence
int result = 2 + 3 * 4;
The result is 14, not 20, because multiplication is evaluated before addition.
Correction: Write (2 + 3) * 4 if the intended result is 20.
Mistake 5: Dividing an Integer by Zero
int a = 10;
int b = 0;
// int result = a / b; // Throws ArithmeticException
Correction: Validate the divisor before performing integer division.
Mistake 6: Confusing Logical and Bitwise Operators
&& and || perform conditional logical evaluation with short-circuiting. The operators & and | can operate on boolean operands without short-circuiting, or on integral operands bit by bit.
Mistake 7: Using Increment Operators in Complicated Expressions
int a = 5;
int result = a++ + ++a;
System.out.println(result);
Although Java defines the evaluation rules, mixing several side effects in one expression makes code harder to read and maintain. Prefer separate statements when possible.
21. Practical Example: Student Marks Calculator
This example combines arithmetic, comparison, logical, and assignment operators to calculate a student's average and determine whether the student has passed.
public class MarksCalculator {
public static void main(String[] args) {
int subject1 = 80;
int subject2 = 75;
int subject3 = 90;
int total = subject1 + subject2 + subject3;
double average = total / 3.0;
boolean passedAllSubjects =
subject1 >= 40 &&
subject2 >= 40 &&
subject3 >= 40;
String result = passedAllSubjects
? "Pass"
: "Fail";
System.out.println("Total: " + total);
System.out.println("Average: " + average);
System.out.println("Result: " + result);
}
}
Output
Total: 245
Average: 81.66666666666667
Result: Pass
Operators Used
+ calculates the total marks.
/ calculates the average using floating-point division.
>= compares each subject mark with the passing threshold.
&& requires every subject condition to be true.
? : selects the result text based on the boolean condition.
= assigns calculated values to variables.
22. Practical Example: Shopping Bill Calculator
This program demonstrates multiplication, addition, compound assignment, and conditional expressions in a basic shopping scenario.
public class ShoppingBill {
public static void main(String[] args) {
final double TAX_RATE = 0.18;
double itemPrice = 500.0;
int quantity = 3;
double subtotal = itemPrice * quantity;
double tax = subtotal * TAX_RATE;
double total = subtotal;
total += tax;
String message = total >= 1500
? "High-value purchase"
: "Regular purchase";
System.out.println("Subtotal: " + subtotal);
System.out.println("Tax: " + tax);
System.out.println("Total: " + total);
System.out.println(message);
}
}
Output
Subtotal: 1500.0
Tax: 270.0
Total: 1770.0
High-value purchase
Note: This example demonstrates operator usage. Production billing systems should use appropriate decimal arithmetic and apply the correct tax, rounding, and currency rules for their requirements.
23. Best Practices for Working with Operators and Expressions
- Use descriptive variable names so expressions are easier to understand.
- Add parentheses when they make the intended evaluation order clearer.
- Avoid combining multiple increments, assignments, or method side effects in one complex expression.
- Use
&& and || for normal conditional logic when short-circuiting is desired.
- Use
equals() or an appropriate comparison method when comparing object content.
- Check for zero before integer division or remainder operations.
- Be aware of integer overflow and floating-point precision limitations.
- Use explicit casting when a conversion is intended and safe.
- Prefer readable conditional statements over deeply nested ternary expressions.
- Use appropriate numeric types for the problem, especially when dealing with financial calculations.
- Test boundary conditions, such as zero, negative numbers, maximum values, and empty input.
- Consult the Java Language Specification for the formal rules governing operators, expressions, precedence, and evaluation.
24. Practical Exercises
Exercise 1: Arithmetic Operators
Create a program with two integer variables and display their sum, difference, product, quotient, and remainder.
Exercise 2: Even or Odd
Use the remainder operator to determine whether a given integer is even or odd.
Exercise 3: Comparison Operators
Declare two numbers and print the results of <, >, <=, >=, ==, and !=.
Exercise 4: Logical Conditions
Create a program that checks whether a person is at least 18 years old and has a valid identification document. Use && to combine the conditions.
Exercise 5: Prefix and Postfix
Initialize an integer to 10 and demonstrate the difference between ++number and number++. Print the expression results and the variable values.
Exercise 6: Ternary Operator
Write a program that uses the conditional operator to display Pass when marks are at least 40 and Fail otherwise.
Exercise 7: Operator Precedence
Evaluate the following expressions manually, then verify them using Java:
int a = 10 + 2 * 5;
int b = (10 + 2) * 5;
int c = 20 - 5 - 3;
int d = 18 / 4;
Exercise 8: Shopping Calculator
Calculate a bill from item price and quantity, add a tax amount, and use a comparison operator to check whether the total exceeds a chosen threshold.
25. Interview Questions and Answers
Q1. What is an operator in Java?
Answer: An operator is a symbol or token that performs an operation on one or more operands, such as addition, comparison, assignment, or logical evaluation.
Q2. What is an expression?
Answer: An expression is a combination of operands, operators, and possibly method calls that evaluates to a value or produces a result.
Q3. What is the difference between = and ==?
Answer: The = operator assigns a value, whereas == checks equality. For object references, == tests reference identity.
Q4. What is the difference between / and %?
Answer: The division operator / calculates a quotient, while the remainder operator % returns the remainder from division.
Q5. What is the difference between prefix and postfix increment?
Answer: Prefix increment updates the variable before the expression produces its value. Postfix increment produces the original value and then updates the variable.
Q6. What is short-circuit evaluation?
Answer: Short-circuit evaluation means Java skips evaluating the right operand of && when the left operand is false and skips the right operand of || when the left operand is true.
Q7. What is operator precedence?
Answer: Operator precedence determines how operators are grouped in an expression when parentheses do not explicitly determine the grouping.
Q8. What is operator associativity?
Answer: Associativity determines how operators of the same precedence are grouped. For example, subtraction groups from left to right, while assignment groups from right to left.
Q9. What is the ternary operator?
Answer: The ternary operator ? : selects one of two expressions based on a boolean condition.
Q10. What is the difference between && and &?
Answer: && performs conditional logical AND with short-circuit evaluation. & can perform bitwise AND on integral values or non-short-circuit logical AND on boolean values.
Q11. What happens when an integer is divided by zero?
Answer: Integer division by zero throws an ArithmeticException.
Q12. Why does 5 / 2 produce 2 in Java?
Answer: Both operands are integers, so Java performs integer division and discards the fractional part toward zero.
Q13. How do you compare the contents of two strings?
Answer: Use equals() to compare string content. The == operator checks whether two references refer to the same object.
Q14. What are bitwise operators used for?
Answer: Bitwise operators manipulate individual bits of integral values and are useful for flags, masks, and low-level data processing.
Q15. What is the instanceof operator?
Answer: The instanceof operator checks whether an object is compatible with a specified type.
26. Quick Revision Checklist
- An operator performs an operation on one or more operands.
- An expression combines operands and operators to produce a result.
- Arithmetic operators include
+, -, *, /, and %.
- Relational and equality operators produce boolean results.
- Logical operators combine or reverse boolean conditions.
- Assignment operators assign or update values.
- Prefix and postfix increment differ in the value produced by the expression.
- Bitwise operators manipulate individual bits.
- Shift operators move bits left or right.
- The ternary operator provides a compact conditional expression.
- Operator precedence and associativity determine expression grouping.
- Integer division discards the fractional part toward zero.
- Short-circuit operators can skip evaluating the right operand.
- Parentheses improve clarity and help express intended grouping.
27. Conclusion
Java operators and expressions are essential for performing calculations, comparing data, assigning values, manipulating bits, and implementing decision-making logic. Understanding each operator category helps you write accurate and readable programs, while knowledge of precedence, associativity, type conversion, and short-circuit evaluation helps prevent common programming mistakes.
Continue practicing with small Java programs before combining multiple operators into larger applications. As your skills develop, apply these concepts to calculations, validation, loops, conditional statements, object-oriented programming, and real-world business logic.
To continue your learning journey, explore the Core Java Training Course, register through the JustAcademy course demo page, or visit the JustAcademy website.